package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 报表控制层
 */
@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference
    private MemberService memberService;

    @Reference
    private SetmealService setmealService;

    @Reference
    private ReportService reportService;

    /**
     * 会员数量统计报表
     *
     * @return
     */
    @RequestMapping(value = "/getMemberReports",method = RequestMethod.POST)
    public Result getMemberReport(@RequestBody String[] dateValuel) {
        String startDate = dateValuel[0].substring(0,10);
        String endDate = dateValuel[1].substring(0,10);


        try {
            //指定日期的每一个月份
            List<String> months = getRangeSet(startDate,endDate);

            //查询每个月的会员数量
            List<Integer> counts = new ArrayList<>();
            for (String month : months) {
                Integer count = memberService.findMemberCountBeforeDate(month);
                counts.add(count);
            }
            Map<String, Object> map = new HashMap<>();
            map.put("months", months);
            map.put("memberCount", counts);

            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }

    private static List<String> getRangeSet(String startDate, String endDate) {
        List<String> rangeSet = null;
        SimpleDateFormat sdf = null;
        Date begin_date = null;
        Date end_date = null;
        //rangeSet = new java.util.ArrayList<>();
        rangeSet = new ArrayList<>();
        sdf = new SimpleDateFormat("yyyy-MM");

        try {
            begin_date = sdf.parse(startDate);//定义起始日期
            end_date = sdf.parse(endDate);//定义结束日期
        } catch (ParseException e) {
            e.printStackTrace();
            System.out.println("时间转换异常，请检查你的时间格式是否为yyyy-MM");
        }
        Calendar calendar = Calendar.getInstance();//定义日期实例
        calendar.setTime(begin_date);//设置日期起始时间
        while (!calendar.getTime().after(end_date)){//判断是否到结束日期
            rangeSet.add(sdf.format(calendar.getTime()));
            calendar.add(Calendar.MONTH,+1);//进行当前日期月份加1

        }
        return rangeSet;
    }

    @GetMapping("/getMemberReport")
    public Result getMemberReport() {
        try {
            //获取这一年的月份
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MONTH, -12);//获得当前日期之前12个月的日期

            List<String> months = new ArrayList<>();
            for (int i = 0; i < 12; i++) {
                calendar.add(Calendar.MONTH, 1);//循环遍历12次，每次向前1个月
                months.add(new SimpleDateFormat("yyyy-MM").format(calendar.getTime()));
            }
            //查询每个月的会员数量
            List<Integer> counts = new ArrayList<>();
            for (String month : months) {
                Integer count = memberService.findMemberCountBeforeDate(month);
                counts.add(count);
            }
            Map<String, Object> map = new HashMap<>();
            map.put("months", months);
            map.put("memberCount", counts);
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }





    /**
     * 套餐饼状图统计
     * @return
     */
    @GetMapping("/getSetmealReport")
    public Result getSetmealReport() {
        try {
            Map<String, Object> map = setmealService.getSetmealReport();
            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    /**
     * 运营数据统计
     */
    @GetMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
        try {
            Map<String, Object> map = reportService.getBusinessReportData();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    /**
     * 导出运营数据
     */
    @GetMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> result = reportService.getBusinessReportData();

            //获得Excel模板文件绝对路径
            String temlateRealPath = request.getSession().getServletContext().getRealPath("template") +
                    File.separator + "report_template.xlsx";

            //获取模板对象
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(new FileInputStream(new File(temlateRealPath)));

            //通过第三方模板技术
            //针对POI开发模板技术
            XLSTransformer transformer = new XLSTransformer();
            transformer.transformWorkbook(xssfWorkbook, result);


            //通过输出流进行文件下载
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
            xssfWorkbook.write(out);

            out.flush();
            out.close();
            xssfWorkbook.close();

            return null;

        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL,null);
        }
    }
    /**
     * 性别占比统计
     * 黄剑锋
     */
    @GetMapping("/getSexReport")
    public Result getSexReport(){

        try {
            Map<String,Object> map = memberService.getSexReport();
            return new Result(true,MessageConstant.GET_SEX_COUNT_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();

            return new Result(false,MessageConstant.GET_SEX_COUNT_REPORT_FAIL);
        }
    }

    /**
     * 年龄段占比统计
     */
    @GetMapping("/getAgeReport")
    public  Result getAgeReport(){

        try {
            Map<String, Object> map = memberService.getAgeReport();
            return new Result(true,MessageConstant.GET_AGE_COUNT_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_AGE_COUNT_REPORT_FALL);
        }
    }

}
